package com.hzit.sk.controller;

import com.hzit.sk.constant.RedisKeyConstant;
import com.hzit.sk.resp.Response;
import com.hzit.sk.service.IOrderService;
import com.hzit.sk.service.ISkillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/skill")
public class SkillController {

    @Autowired
    private ValueOperations valueOperations;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISkillService skillService;

    Logger logger = LoggerFactory.getLogger(SkillController.class);



    /**
     * 1.生成隐藏地址
     * @return
     */
    @ResponseBody
    @RequestMapping("/path")
    public Response<String> getPath(@RequestParam("goodsId") String goodsId,
                          @RequestParam("userId") String userId){

//       ValueOperations valueOperations = stringRedisTemplate.opsForValue();

        //1.生成uuid 作为隐藏的接口地址
        String path = UUID.randomUUID().toString().replace("-","");

        //2.放到redis中
        valueOperations.set(RedisKeyConstant.SKILL_PATH + userId+ goodsId,path,5, TimeUnit.MINUTES);
        Response<String> response = Response.getSuccessData("请求成功");
        response.setData(path);
        return response;
    }

    /**
     * 开始秒杀
     * 1.接口防刷。隐藏接口地址。
     * 2.限制1分钟访问5次. aop,+ ip 的计数器
     * @return
     */
    @ResponseBody
    @RequestMapping("/{path}/goods/{goodsId}/{userId}")
    public Response doSkill(@PathVariable("path")String path,
                          @PathVariable("goodsId")String goodsId,
                          @PathVariable("userId")String userId){

        logger.info("请求参数path：{},goodsId:{},userId:{}",path,goodsId,userId);


        Response response =  skillService.skill( userId,  goodsId, path);

        return response;

    }

    /**
     * 获取订单生成结果
     * @return
     */
    @ResponseBody
    @RequestMapping("/result")
    public Response<String> querySkillResult(@RequestParam("goodsId") String goodsId,
                                     @RequestParam("userId") String userId){

        logger.info("获取订单生成结果，goodsId:{},userId:{}",goodsId,userId);

        return orderService.queryOreder(userId,goodsId);

    }



}
